package com.tensquare.user.controller;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2019/9/21 10:39
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.发送手机验证码
    @PostMapping("sendsms/{mobile}")
    public Result sendMessage(@PathVariable String mobile){
        //1.1)发送手机验证码
        userService.sendCode(mobile);
        //1.2)返回结果
        return new Result(true,StatusCode.OK,"发送验证码成功！");
    }
    //2.添加用户
    @PostMapping
    public Result add(@RequestBody User user){
        //2.1)添加用户
        userService.add(user);
        //2.2)返回
        return new Result(true,StatusCode.OK,"添加用户成功！");
    }
    //3.用户登录
    @PostMapping("login")
    public Result login(@RequestBody User user){
        //3.1)用户登录
        User loginUser = userService.login(user);
        //生成token
        String token = jwtUtil.createJwt(loginUser.getId(), loginUser.getNickname(), "user");

        //3.2)判断
        if(loginUser != null){
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("name",loginUser.getNickname());
            return new Result(true,StatusCode.OK,"用户登录成功！",map);
        }
        return new Result(false,StatusCode.ERROR,"用户登录失败！");
    }
    //4.删除用户
    @DeleteMapping("{userId}")
    public Result delete(@PathVariable String userId){
        //4.1)从请求作用域中得到以claims为key的值
        Claims claims = (Claims) request.getAttribute("claims");
        //4.2)得到其中以roles为key的值
        if(claims != null ){
            //4.3)得到角色信息
            String roles = (String) claims.get("roles");
            //4.4)判断
            if(StringUtils.isNotBlank(roles) && "admin".equals(roles)){
                userService.delete(userId);
                return new Result(true,StatusCode.OK,"删除用户成功！");
            }
        }
        return new Result(false,StatusCode.ERROR,"无删除用户权限！");
    }

    //5.更新粉丝数
    @PostMapping("incfans/{friendid}/{x}")
    public void incfans(@PathVariable String friendid,@PathVariable int x){
        userService.incfans(friendid,x);
    }
    //6.更新关注数
    @PostMapping("incfollow/{userid}/{x}")
    public void incfollow(@PathVariable String userid,@PathVariable int x){
        userService.incfollow(userid,x);
    }
}
